package cn.itcast.bos.service.base.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.bos.dao.CourierDao;
import cn.itcast.bos.domain.base.Courier;
import cn.itcast.bos.service.base.CourierSerivce;
@Service
@Transactional
public class CourierSerivceImpl implements CourierSerivce{
	@Autowired
	private CourierDao courierDao;
	
	@Override
	public void saveCourier(Courier courier) {
		courierDao.save(courier);
		
	}

    @Override
    public Page<Courier> pageQuery(Pageable pageable, Courier courier) {
    	//分页条件查询
    	Specification<Courier> specification = new Specification<Courier>() {
			
			
			public Predicate toPredicate(Root<Courier> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> list = new ArrayList();
				if(StringUtils.isNotBlank(courier.getCourierNum())){
					Predicate p1 = cb.equal(root.get("courierNum").as(String.class), courier.getCourierNum());
					list.add(p1);
				}
				if(StringUtils.isNotBlank(courier.getCompany())) {
					Predicate p2 = cb.like(root.get("company").as(String.class), "%"+courier.getCompany()+"%");
					list.add(p2);
				}
				if(StringUtils.isNotBlank(courier.getType())) {
					Predicate p3 = cb.equal(root.get("type").as(String.class), courier.getType());
					list.add(p3);
				}
				Join<Object, Object> standroot = root.join("standard",JoinType.INNER);
				if(courier.getStandard()!=null &&StringUtils.isNotBlank(courier.getStandard().getName())){
					Predicate p4 = cb.like(standroot.get("name").as(String.class), "%"+courier.getStandard().getName().trim()+"%");
					list.add(p4);
				}
				return cb.and(list.toArray(new Predicate[list.size()]));
			}
		};

        return courierDao.findAll(specification, pageable);
        
    }

	@Override
	public void delete(String ids) {
		String[] id = ids.split(",");
		for (String str : id) {
			courierDao.deleteTag(Integer.parseInt(str));
			
		}
		
	}

    @Override
    public List<Courier> findNoAssociation() {
		//封装speciation
		Specification<Courier> specification = new Specification<Courier>() {
			@Override
			public Predicate toPredicate(Root<Courier> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				Predicate p = cb.isEmpty(root.get("fixedAreas").as(Set.class));
				return p;
			}
		};
         return courierDao.findAll(specification);
    }

}
